package com.imb.security;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imb.common.mybatis.entity.ImbUser;
import com.imb.common.mybatis.mapper.ImbUserMapper;
import com.imb.common.web.exception.CustomException;
import com.imb.common.web.model.LoginUser;
import com.imb.common.web.model.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 重写security的UserDetailsService接口，用来与数据库交互，查询用户信息
 * @author xiaozhi
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ImbUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据用户名查询用户信息
        ImbUser user=getUser(username);
        UserDetail detail= BeanUtil.toBean(user, UserDetail.class);
        //TODO 根据用户查询权限信息 添加到LoginUser中
//        List<String> list=sysMenuMapper.menuList(user.getUserId());
        //封装成UserDetails对象返回
        return new LoginUser(detail,null,detail.getUserName(),detail.getPassword());
    }


    public ImbUser getUser(String username){
        LambdaQueryWrapper<ImbUser> userLambdaQueryWrapper= Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(ImbUser::getUserName,username)
                .last("limit 1");
        ImbUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper);
        if(Objects.isNull(sysUser)){
            throw new CustomException("用户或者密码为错误！");
        }
        return sysUser;
    }
}
